package com.bzr.emos.wx.config.security;

import com.alibaba.fastjson2.JSON;
import com.bzr.emos.wx.config.jwt.JwtAuthenticationFilter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;

import java.util.HashMap;

@Configuration
public class SecurityConfiguration {
    @Resource
    private UserDetailsService service;

    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;


    @Bean
    public AuthenticationManager authenticationManager() {
        //匹配合适的AuthenticationProvider(DaoAuthenticationProvider)
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        //配置基于数据库认证的UserDetailsService对象
        provider.setUserDetailsService(service);
        //创建并返回认证管理器对象(实现类ProviderManager)
        return new ProviderManager(provider);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                        .requestMatchers("/login").permitAll()
                        .requestMatchers("/verify/VerifyLogin").permitAll()
                        .requestMatchers("/verify/activation").permitAll()
                        .requestMatchers("/register/avatar").permitAll()
                        .anyRequest().authenticated()).logout(logout -> logout
                .logoutSuccessHandler((request, response, authentication) -> {
                    // 1. 清除指定Cookie
                    clearSpecificCookies(response, "DlToken", "JSESSIONID", "remember-me");
                    response.setContentType("application/json;charset=utf-8");
                    HashMap<Object, Object> result = new HashMap();
                    result.put("code", 0);//成功
                    result.put("message", "注销成功");
                    //将结果转换成JSON字符串
                    String json = JSON.toJSONString(result);
                    response.getWriter().println(json);
                }).deleteCookies("JSESSIONID", "DlToken")
                        .invalidateHttpSession(true) // 使Session失效
                        .clearAuthentication(true) // 清除认证信息
                // 注销成功后跳转到首页
                .logoutSuccessUrl("/login")
        )
                .csrf(csrf->csrf.disable())
                .addFilterBefore(jwtAuthenticationFilter, AuthorizationFilter.class)
                .formLogin(form -> form.disable());
        return http.build();
    }


    private void clearSpecificCookies(HttpServletResponse response, String... cookieNames) {
        for (String cookieName : cookieNames) {
            Cookie cookie = new Cookie(cookieName, null);
            cookie.setPath("/"); // 必须与设置时的路径一致
            cookie.setHttpOnly(true);
            cookie.setMaxAge(0); // 立即过期
            cookie.setSecure(true); // 如果使用HTTPS
            response.addCookie(cookie);
        }
    }
}
